import Cookies from "js-cookie"

export default {
    state: {
        // 控制菜单的展开还是收起
        isCollapse: false, 
        //面包屑数据
        tabsList: [{
            path: "/",
            name: "home",
            label: "首页",
            icon: "s-home",
            url: "Home",
        }],
        //动态菜单数据
        menu :[]
    },

    mutations: {
        // 修改菜单展开收起的方法
        collapseMenu(state) {
            state.isCollapse = !state.isCollapse
        },

        selectMenu(state, val) {
            console.log(val, 'val')
            //当前页面路由和跳转路由不一致才允许跳转
            if (val.path !== 'home') {
                const index = state.tabsList.findIndex(item => item.name === val.name)
                //如果不存在
                if (index === -1) {
                    state.tabsList.push(val)
                }

            }
        },

        setMenu(state, val) {
            state.menu = val
            // localStorage.setItem('menu', JSON.stringify(val))
            Cookies.set('menu', JSON.stringify(val))
        },
        addMenu(state, router) {
            // if (!localStorage.getItem('menu')) {
            //     return
            // }
            // const menu = JSON.parse(localStorage.getItem('menu'))

            if (!Cookies.get('menu')) {
                return
            }
            const menu = JSON.parse(Cookies.get('menu'))

            state.menu = menu
            const menuArray = []
        
            menu.forEach(item => {
                if (item.children) {
                    item.children = item.children.map(item => {
                        let url = `../views/${item.url}`          
// component: (resolve) => require([`@/views/${type}/index.vue`] ,resolve)
                        // item.component = () => import(url)
                        item.component= (resolve) => require([`@/views/${item.url}`], resolve)

                        return item
                    })
                    //扩展运算符，，展开封给数组
                    menuArray.push(...item.children)
                } else {
                    let url = `../views/${item.url}`
                    // item.component = () => import(url)
                    item.component= (resolve) => require([`@/views/${item.url}`], resolve)
                    menuArray.push(item)
                }
            })
            console.log(menuArray,'menuArray')
            menuArray.forEach(item => {
                router.addRoute('Main', item)
            })
        },
    }
}